package com.zoweunion.mechanic.controller.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.config.RabbitMQForLoginConfig;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.dao.base.UserDao;
import com.zoweunion.mechanic.dao.shangji.ShangJiMapper;
import com.zoweunion.mechanic.entity.DeptEntity;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.plugins.mq.RabbitMQCustomer;
import com.zoweunion.mechanic.plugins.shiro.JWTUtil;
import com.zoweunion.mechanic.service.DeptService;
import com.zoweunion.mechanic.service.UserCouponService;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.base.OwnerService;
import com.zoweunion.mechanic.service.base.UserService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private OwnerService ownerService;
	@Autowired
	private AppService appService;
	@Autowired
	private UserCouponService userCouponService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private RabbitMQCustomer rabbitMQCustomer;
	@Autowired
	private UserDao userDao;
	@Autowired
	private RabbitMQForLoginConfig rmqlc;
	@Autowired
	private ShangJiMapper shangJiMapper;
	@Autowired
	private RestTemplate restTemplate;
	@Value("${APISpace.X-APISpace-Token}")
	private String xAPISpaceToken;
	@Value("${kapool.userid}")
	private String kapoolUserId;
	@Value("${kapool.sign}")
	private String kapoolSign;

	@PostMapping(value = "/testPost", produces = {"application/json;charset=UTF-8"})
	public String testPost(@RequestBody JSONObject obj) {
		logBefore(logger, "testPost");
		String jsonStr = obj.toJSONString();
		logAfter(logger);
		return jsonStr;
	}

	@GetMapping(value = "/testGet", produces = {"application/json;charset=UTF-8"})
	public String testGet() {
		logBefore(logger, "getUser");
		String jsonStr = "";
		logAfter(logger);
		return jsonStr;
	}

	/**
	 * 用户登录,验证用户名密码,返回用户及用户关联的角色数据
	 */
	@PostMapping("/doLogin")
	public ResponseBean login(@RequestBody String str) {
		logBefore(logger, "用户登录");
		//1.验证用户名密码
		User reqUser = JSONObject.parseObject(str,User.class);
		User existUser = userService.getUserByAccount(reqUser.getUser_account());
		if(existUser == null) {
			return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "该用户不存在",null);
		}
		if (!existUser.getUser_password().equals(MD5.md5(reqUser.getUser_password()))){
			return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "用户名或密码错误", null);
		} else {
				//2.验证通过查询具体用户信息并返回
				Map<String, Object> userInfo1 = userService.getUserInfoByAccount(reqUser.getUser_account());
				Optional<Map<String, Object>> optional = Optional.ofNullable(userInfo1);
				if (optional.isPresent()) {
					Optional<Map<String, Object>> optional1 = optional.map((Map<String, Object> userInfoMap) -> {
						//2.1生成JWTtoken
						userInfoMap.put("Authorization", JWTUtil.sign(userInfoMap.get("user_account").toString(),userInfoMap.get("user_password").toString()));
						return userInfoMap;
					});
					try {
						this.sendMQMessage(userInfo1.get("id").toString());
					}catch (Exception e){
						e.printStackTrace();
					}
					return new ResponseBean(Constants.CODE_SUCCESS, "登录成功",optional1.get());
				} else {
					return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "用户名或密码错误", null);
				}
		}
	}

	public void sendMQMessage(String userId) {
		String message = "{\"type\" : 2}";	// type=2 后市场单方登录：强制退出登录
		// System.out.println("生产者产生的消息: " + message + userId);

		// routingKey 为虚拟的队列名称，与前端约定一致的uuid(设置为userId)(路由器需要设置为direct定向，把消息交给符合指定routing key的队列)
		RabbitTemplate rabbitTemplateForLogin = rmqlc.rabbitTemplateForLogin();
		rabbitTemplateForLogin.convertAndSend("amq.direct", userId, message);
	}

	/**
	 * 用户登录,验证用户名密码,返回用户及用户关联的角色数据
	 */
	@PostMapping("/modifyUserPassword")
	public ResponseBean modifyUserPassword(@RequestBody String str,HttpServletRequest request) throws MyException {

		logBefore(logger, "修改用户密码");

		Map<String,Object> reqObj = JSONObject.parseObject(str,Map.class);

		reqObj.put("user_id",getCurrentUser(request).getId());

        String passWord_md5 = MD5.md5((String) reqObj.get("password"));

        reqObj.put("user_password",passWord_md5);
        reqObj.put("password_md5",passWord_md5);

		userService.recordUserPassword(reqObj);

        // user_account
		userService.updatePassWord(reqObj);

		return new ResponseBean(Constants.CODE_SUCCESS, "密码修改成功",null);
	}

	/**
	 * 用户注册
	 * 车主注册 和 app 端用户注册 和 服务商添加用户
	 */
	@PostMapping("doRegister")
	public ResponseBean register(@RequestBody String str,HttpServletRequest request){
		logBefore(logger, "注册用户");
		Map<String,Object> reqObj = JSONObject.parseObject(str,Map.class);
		ResponseBean responseBean = new ResponseBean();
		int code = Constants.CODE_ERROR;
		String message = "";
		String currentUserId=null;
		String userName=null;
		String currentUserSId=null;
		try {
			//根据请求头判断当前是游客操作还是后台管理员操作
			String authorization = request.getHeader("Authorization");
			if(authorization!=null) {
				String user_account = JWTUtil.getUsername(authorization);
				User currentUser = userService.getUserByAccount(user_account);
				if(currentUser!=null) {
					currentUserId=currentUser.getId();
					userName=currentUser.getUser_name();
					currentUserSId=currentUser.getS_id();
				}
			}
			if(reqObj.get("mobile_phone")!=null && !reqObj.get("mobile_phone").equals("")
					&& reqObj.get("user_name")!=null && !reqObj.get("user_name").equals("")) {
				//1.查询并判断账号是否已存在
				Map<String, Object> userInfo=userService.getUserInfoByAccount(reqObj.get("mobile_phone").toString());
				if (userInfo != null) {
					// 判断如果已存在账号是游客可改为任意角色
					if (currentUserSId != null && userInfo.get("r_id") != null && !userInfo.get("r_id").equals("")) {
						userInfo.put("s_id", currentUserSId);
						userInfo.put("r_id", reqObj.get("r_id"));
						userInfo.put("user_name", reqObj.get("user_name"));
						userInfo.put("sexy", reqObj.get("sexy"));
						userInfo.put("card_id", reqObj.get("card_id"));
						userInfo.put("update_user", currentUserId);
						if (Constants.ROLE_CZ.equals(userInfo.get("r_id").toString())) {
							userInfo.put("area", reqObj.get("area"));
							userInfo.put("address", reqObj.get("address"));
							userInfo.put("shieldPrice", reqObj.get("shieldPrice"));
						} else {
							userInfo.put("speciality", reqObj.get("speciality"));
						}
						userInfo.put("update_user", currentUserId);
						userInfo.put("user_password", reqObj.get("user_password"));
						userService.update(userInfo);

						if (!Constants.ROLE_CZ.equals(userInfo.get("r_id").toString())) {
							// 如果是车主，为此人员添加管辖区域
							Object provinceListObj = reqObj.get("provinceList");
							if (provinceListObj != null) {
								appService.addUserAssignRegion((List<Map<String, Object>>) provinceListObj, userInfo.get("id").toString()
										, currentUserSId, currentUserId);
							}
						}

						// 判断该操作是否为绑定车主  并且未绑定服务商 true则绑定该车主到服务商
						if (userInfo.get("r_id") != null && userInfo.get("r_id").equals(Constants.ROLE_CZ) &&
								userInfo.get("s_id") != null) {
							// 移除所有绑定的车辆
							ownerService.deleteCarByOwner(userInfo.get("id").toString());
							// 绑定车辆
							if (reqObj.get("carList") != null) {
								List<Map<String, Object>> carList = (List<Map<String, Object>>) reqObj.get("carList");
								for (Map<String, Object> ownerCarMap : carList) {
									ownerCarMap.put("o_id", userInfo.get("id"));
									ownerService.bindingCar(ownerCarMap);
								}
							}
						}
						try {
							Map<String, Object> reqMap = new HashMap<>();
							reqMap.put("s_id", currentUserSId);
							Map<String, Object> serverMap = userDao.getServerInfoBySId(reqMap);
							reqMap.put("s_name", Orgin.getString(serverMap, "user_name"));
							if (userInfo.get("r_id") != null && userInfo.get("r_id").equals(Constants.ROLE_CZ)) {
								//日志系统操作记录-车主管理_新增
								rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("车主管理"), Constants.OperationType.getOperationTypeCode("新增"),
								currentUserId, userName, Orgin.getString(userInfo, "id"), Orgin.getString(userInfo, "user_name"),
										"", "", currentUserSId, Orgin.getString(reqMap, "s_name"), "");
							} else {
								//日志系统操作记录-人员管理-新增
								rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("人员管理"), Constants.OperationType.getOperationTypeCode("新增"),
								currentUserId, userName, Orgin.getString(userInfo, "id"), Orgin.getString(userInfo, "user_name"),
										"", "", currentUserSId, Orgin.getString(reqMap, "s_name"), "");
							}
						} catch (Exception e) {
							e.printStackTrace();
							logger.error(e.getMessage());
						}
						code = Constants.CODE_SUCCESS;
						message = "绑定成功";
					} else {
						code = Constants.CODE_HANDEL_FAILED;
						message = "账号已存在";
					}
				} else {
					//2注册用户
					reqObj.put("update_user",currentUserId);
					reqObj.put("create_user",currentUserId);
					reqObj.put("s_id",currentUserSId);
					String userId = userService.doRegister(reqObj);
					//登录领取优惠券
					userCouponService.getCouponByRegister(userId,reqObj.get("mobile_phone").toString());
					// 如果是服务商添加人员，为人员添加管辖区域
					Object provinceListObj = reqObj.get("provinceList");
					if (provinceListObj != null) {
						appService.addUserAssignRegion((List<Map<String, Object>>) provinceListObj, userId, currentUserSId, currentUserId);
					}
					// 绑定车辆
					if (reqObj.get("carList") != null) {
						List<Map<String, Object>> carList = (List<Map<String, Object>>) reqObj.get("carList");
						for (Map<String, Object> ownerCarMap : carList) {
							ownerCarMap.put("o_id", userId);
							ownerService.bindingCar(ownerCarMap);
						}
					}
					try {
						Map<String, Object> serverMap = userDao.getServerInfoBySId(reqObj);
						if(serverMap != null) {
							serverMap.put("s_name", Orgin.getString(serverMap, "user_name"));
							String r_id = Orgin.getString(userService.getUserById(userId), "r_id");
							if (r_id != null && r_id.equals(Constants.ROLE_CZ)) {
								//日志系统操作记录-车主管理_新增
								rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("车主管理"), Constants.OperationType.getOperationTypeCode("新增"),
										currentUserId, userName, userId, Orgin.getString(reqObj, "user_name"),
										"", "", currentUserSId, Orgin.getString(serverMap, "s_name"), "");
							} else {
								//日志系统操作记录-人员管理-新增
								rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("人员管理"), Constants.OperationType.getOperationTypeCode("新增"),
										currentUserId, userName, userId, Orgin.getString(reqObj, "user_name"),
										"", "", currentUserSId, Orgin.getString(serverMap, "s_name"), "");
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
						logger.error(e.getMessage());
					}
					code = Constants.CODE_SUCCESS;
					message = "注册成功";
				}
			} else {
				code = Constants.CODE_HANDEL_FAILED;
				message = "注册失败，请检查注册信息";
			}
		} catch (Exception e) {
			code=Constants.CODE_ERROR;
			message="发生异常";
			logger.error(e.toString(), e);
		} finally {
			responseBean.setCode(code);
			responseBean.setMessage(message);
			logAfter(logger);
		}
		return responseBean;
	}

	/**
	 * 后市场用户保存用户(关联部门)-add 2022年3月7日10:30:48
	 */
	@PostMapping("saveUser")
	public ResponseBean saveUser(@RequestBody String str,HttpServletRequest request) throws MyException {
		logBefore(logger, "后市场保存用户");
		Map<String,Object> reqObj = JSONObject.parseObject(str,Map.class);
		ResponseBean responseBean = new ResponseBean();
		int code = Constants.CODE_ERROR;
		String message = "";
		User user = getCurrentUser(request);
		String currentUserId= user.getId();
		String currentUserSId = user.getS_id();
		String userName = user.getUser_name();

		if(reqObj.get("mobile_phone") != null && !reqObj.get("mobile_phone").equals("")
				&& reqObj.get("user_password") != null && !reqObj.get("user_password").equals("")
				&& reqObj.get("user_name") != null && !reqObj.get("user_name").equals("")
				&& reqObj.get("dept_id") != null && !reqObj.get("dept_id").equals("")) {
			// 查询并判断账号是否已存在
			Map<String, Object> userInfo = userService.getUserInfoByAccount(reqObj.get("mobile_phone").toString());
			if (userInfo == null) {
				// 保存用户
				reqObj.put("create_user", currentUserId);
				reqObj.put("s_id", currentUserSId);

				// 转换前端提交结构 goodatdicId
				if(reqObj.get("goodatdicId") != null){

					// 把前端传过来的[1,2,3]转换成字符串 1,2,3
					JSONArray goodatdicIdJsonArray = (JSONArray) reqObj.get("goodatdicId");
					String goodatdicIdString = FunUtil.implode(goodatdicIdJsonArray,",");
					reqObj.put("goodatdicId",goodatdicIdString);
				}

				String userId = userService.doRegister(reqObj);

				//插入用户与部门关系表
				deptService.insertRelation(DeptEntity.builder()
						.userId(userId)
						.deptId(Integer.parseInt(reqObj.get("dept_id").toString()))
						.sId(currentUserSId)
						.build());

				// 登录领取优惠券
				userCouponService.getCouponByRegister(userId,reqObj.get("mobile_phone").toString());
				// 添加管辖区域
				Object provinceListObj = reqObj.get("provinceList");
				if (provinceListObj != null) {
					appService.addUserAssignRegion((List<Map<String, Object>>) provinceListObj, userId, currentUserSId, currentUserId);
				}

				Map<String, Object> serverMap = userDao.getServerInfoBySId(reqObj);
				serverMap.put("s_name", Orgin.getString(serverMap, "user_name"));
				//日志系统操作记录-人员管理-新增
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("人员管理"), Constants.OperationType.getOperationTypeCode("新增"),
						currentUserId, userName, userId, Orgin.getString(reqObj, "user_name"),
						"", "", currentUserSId, Orgin.getString(serverMap, "s_name"), "");

				code = Constants.CODE_SUCCESS;
				message = "保存成功";
			}
			else {
				code = Constants.CODE_HANDEL_FAILED;
				message = "手机号已存在";
			}
		} else {
			code = Constants.CODE_HANDEL_FAILED;
			message = "保存失败，请检查保存信息";
		}
		logAfter(logger);

		return new ResponseBean(code, message, code == Constants.CODE_SUCCESS ? true : false);
	}

	/**
	 * 后市场用户更新用户(关联部门)-add 2022年3月7日20:16:32
	 * @throws MyException
	 */
	@PostMapping("/editUser")
	public ResponseBean editUser(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "人员管理_编辑");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		reqMap.put("update_user", currentUser.getId());
		reqMap.put("s_id", currentUser.getS_id());

		userService.update(reqMap);

		// 为人员添加管辖区域
		Object provinceListObj = reqMap.get("provinceList");
		if (provinceListObj != null) {
			appService.updateUserAssignRegion((List<Map<String, Object>>) provinceListObj, reqMap.get("id").toString(), currentUser.getS_id(), currentUser.getId());
		}

		//更新用户与部门关系表
		deptService.updateUserRelation(DeptEntity.builder()
				.userId(reqMap.get("id").toString())
				.deptId(Integer.parseInt(reqMap.get("dept_id").toString()))
				.sId(currentUser.getS_id())
				.build());

		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
	}

	/**
	 * 人员管理_查询所有带分页(除车主,司机,游客,管理员)
	 * @throws MyException
	 */
	@PostMapping("/getAllUserByPage")
	public ResponseBean getAllUserByPage(@RequestBody String str, HttpServletRequest request) throws MyException{
		logBefore(logger, "根据服务商id查询所有人员");
		//获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		String s_id = getCurrentUser(request).getS_id();
		/*if (!reqMap.containsKey("role_name")) {
			reqMap.put("role_name",null);
		}
		if (!reqMap.containsKey("user_name")) {
			reqMap.put("user_name", null);
		}
		if (!reqMap.containsKey("user_account")) {
			reqMap.put("user_account", null);
		}
		if (!reqMap.containsKey("sexy")) {
			reqMap.put("sexy", null);
		}
		if (!reqMap.containsKey("status")) {
			reqMap.put("status",null);
		}	*/
		reqMap.put("s_id",s_id);
		Map<String, Object> resultMap = userService.getAllUserByPage(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 人员管理_查询(含客服、听诊、修工、车主、司机,除游客,管理员)
	 * @throws MyException
	 */
    @PostMapping("/getUserInfo")
    public ResponseBean getUserInfo(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "根据userId获取user详细信息");
        //获取当前用户的服务商id
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        String sId = getCurrentUser(request).getS_id();
        Map<String, Object> userInfo = appService.getUserInfoAndAssignRegion(reqMap.get("userId").toString(), sId);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", userInfo);
    }

	/**
	 * 账号管理_查询车主信息
	 * @throws MyException
	 */
    @PostMapping("/getCarMasterInfo")
    public ResponseBean getCarMasterInfo(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "根据userId获取车主的详细信息");
        //获取当前用户的服务商id
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        getCurrentUser(request);
        Map<String, Object> userInfo = appService.getCarMasterInfo(reqMap.get("userId").toString());
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", userInfo);
    }

	/**
	 * 人员管理_查询(含客服、听诊、修工、车主、司机,除游客,管理员)
	 * @throws MyException
	 */
	@PostMapping("/getUser")
	public ResponseBean getUser(@RequestBody String str, HttpServletRequest request) throws MyException{
		logBefore(logger, "根据服务商id查询所有人员");
		//获取当前用户的服务商id
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		reqMap.put("s_id", currentUser.getS_id());
//		reqMap.put("area", currentUser.getArea());
		String searchType = reqMap.get("search_type").toString();
		// 获取当前用的管辖区域, insideTZ-听诊 insideXG-修工
		if ("insideTZ".equals(searchType) || "insideXG".equals(searchType)) {
			reqMap.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers("7".equals(currentUser.getR_id()) ? "" : currentUser.getId(), currentUser.getS_id())));
		}
		List<Map<String, Object>> resultList = userService.getUser(reqMap);
		if(null==resultList){
			reqMap.remove("area");
			resultList=userService.getUser(reqMap);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultList);
	}

	/**
	 * 人员管理_编辑 所有对用户更新的操作都需要获取当前登录用户的id
	 * @throws MyException
	 */
	@PostMapping("/edit")
    public ResponseBean edit(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "人员管理_编辑");
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        User user = getCurrentUser(request);
        reqMap.put("update_user", user.getId());
		if(!(reqMap.get("server_type") != null && Integer.valueOf(reqMap.get("server_type").toString()) == 4)) {
			reqMap.put("s_id", user.getS_id());
		}
        userService.update(reqMap);
        // 如果是服务商添加人员，为人员添加管辖区域
        Object provinceListObj = reqMap.get("provinceList");
        if (provinceListObj != null) {
            appService.updateUserAssignRegion((List<Map<String, Object>>) provinceListObj, reqMap.get("id").toString(), user.getS_id(), user.getId());
        }
//        if (reqMap.get("carList") != null) {
//            // 移除所有绑定的车辆
//            ownerService.deleteCarByOwner(reqMap.get("id").toString());
//            // 绑定车辆
//            List<Map<String, Object>> carList = (List<Map<String, Object>>) reqMap.get("carList");
//            for (Map<String, Object> ownerCarMap : carList) {
//                ownerCarMap.put("o_id", reqMap.get("id"));
//                ownerService.bindingCar(ownerCarMap);
//            }
//        }
		// 16696181768
		try {
			Map<String, Object> serverMap = userDao.getServerInfoBySId(reqMap);
			serverMap.put("s_name", Orgin.getString(serverMap, "user_name"));
			Map<String,Object> operatedUser = userService.getUserById(Orgin.getString(reqMap, "id"));
			String r_id = Orgin.getString(userService.getUserById(Orgin.getString(reqMap, "id")), "r_id");
			if (r_id.equals(Constants.ROLE_CZ)) {
				//日志系统操作记录-车主管理_编辑
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("车主管理"), Constants.OperationType.getOperationTypeCode("编辑"),
				user.getId(), user.getUser_name(), Orgin.getString(reqMap, "id"), Orgin.getString(operatedUser, "user_name"),
						"", "", user.getS_id(), Orgin.getString(serverMap, "s_name"), "");
			} else {
				//日志系统操作记录-人员管理-编辑
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("人员管理"), Constants.OperationType.getOperationTypeCode("编辑"),
				user.getId(), user.getUser_name(), Orgin.getString(reqMap, "id"), Orgin.getString(operatedUser, "user_name"),
						"", "", user.getS_id(), Orgin.getString(serverMap, "s_name"), "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

	/**
	 * 人员管理_禁用
	 * @throws MyException
	 */
	@PostMapping("/ban")
	public ResponseBean ban(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "人员管理_禁用");
		Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);
		String currentUserId = getCurrentUser(request).getId();
		String currentUserName = getCurrentUser(request).getUser_name();
		String currentSiD = getCurrentUser(request).getS_id();
		reqMap.put("update_user",currentUserId);
		reqMap.put("status", 2);
		reqMap.put("s_id", currentSiD);
		userService.update(reqMap);
		try {
			Map<String, Object> serverMap = userDao.getServerInfoBySId(reqMap);
			serverMap.put("s_name", Orgin.getString(serverMap, "user_name"));
			Map<String,Object> operatedUser = userService.getUserById(Orgin.getString(reqMap, "id"));
			String r_id = Orgin.getString(userService.getUserById(Orgin.getString(reqMap, "id")), "r_id");
			if (r_id.equals(Constants.ROLE_CZ)) {
				//日志系统操作记录-车主管理-停用
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("车主管理"), Constants.OperationType.getOperationTypeCode("停用"),
				currentUserId, currentUserName, Orgin.getString(reqMap, "id"), Orgin.getString(operatedUser, "user_name"),
						"", "", currentSiD, Orgin.getString(serverMap, "s_name"), "");
			} else {
				//日志系统操作记录-人员管理-停用
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("人员管理"), Constants.OperationType.getOperationTypeCode("停用"),
				currentUserId, currentUserName, Orgin.getString(reqMap, "id"), Orgin.getString(operatedUser, "user_name"),
						"", "", currentSiD, Orgin.getString(serverMap, "s_name"), "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}

	/**
	 * 人员管理_启用
	 * @throws MyException
	 */
	@PostMapping("/recover")
	public ResponseBean recover(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "人员管理_禁用");
		Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);
		String currentUserId = getCurrentUser(request).getId();
		String currentUserName = getCurrentUser(request).getUser_name();
		String currentSiD = getCurrentUser(request).getS_id();
		reqMap.put("update_user",currentUserId);
		reqMap.put("status", 1);
		reqMap.put("s_id", currentSiD);
		userService.update(reqMap);
		try {
			Map<String, Object> serverMap = userDao.getServerInfoBySId(reqMap);
			serverMap.put("s_name", Orgin.getString(serverMap, "user_name"));
			Map<String,Object> operatedUser = userService.getUserById(Orgin.getString(reqMap, "id"));
			String r_id = Orgin.getString(userService.getUserById(Orgin.getString(reqMap, "id")), "r_id");
			if (r_id.equals(Constants.ROLE_CZ)) {
				//日志系统操作记录-车主管理-启用
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("车主管理"), Constants.OperationType.getOperationTypeCode("启用"),
				currentUserId, currentUserName, Orgin.getString(reqMap, "id"), Orgin.getString(operatedUser, "user_name"),
						"", "", currentSiD, Orgin.getString(serverMap, "s_name"), "");
			} else {
				//日志系统操作记录-人员管理-启用
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("人员管理"), Constants.OperationType.getOperationTypeCode("启用"),
				currentUserId, currentUserName, Orgin.getString(reqMap, "id"), Orgin.getString(operatedUser, "user_name"),
						"", "", currentSiD, Orgin.getString(serverMap, "s_name"), "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}

	/**
	 * 人员管理_删除
	 * @throws MyException
	 */
	@PostMapping("/delete")
	public ResponseBean delete(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "人员管理_删除");
		Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		reqMap.put("update_user", currentUser.getId());
		reqMap.put("delete_flag", 1);
		reqMap.put("s_id", currentUser.getS_id());
		String r_id = Orgin.getString(userService.getUserById(Orgin.getString(reqMap, "id")), "r_id");
		Map<String,Object> operatedUser = userService.getUserById(Orgin.getString(reqMap, "id"));
		userService.update(reqMap);
		// 删除用户的管辖区域
        appService.deleteAssignRegionByUserId(reqMap.get("id").toString());
		try {
			Map<String, Object> serverMap = userDao.getServerInfoBySId(reqMap);
			serverMap.put("s_name", Orgin.getString(serverMap, "user_name"));
			if (r_id.equals(Constants.ROLE_CZ)) {
				//日志系统操作记录-车主管理-删除
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("车主管理"), Constants.OperationType.getOperationTypeCode("删除"),
				currentUser.getId(), currentUser.getUser_name(), Orgin.getString(reqMap, "id"), Orgin.getString(operatedUser, "user_name"),
						"", "", currentUser.getS_id(), Orgin.getString(serverMap, "s_name"), "");
			} else {
				//日志系统操作记录-人员管理-删除
				rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("人员管理"), Constants.OperationType.getOperationTypeCode("删除"),
				currentUser.getId(), currentUser.getUser_name(), Orgin.getString(reqMap, "id"), Orgin.getString(operatedUser, "user_name"),
						"", "", currentUser.getId(), Orgin.getString(serverMap, "s_name"), "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}

	/**
	 * 查询被授予权利的所用符合指定角色的人员(例如:查询高管)
	 * @throws MyException
	 */
	@PostMapping("/getUserWithAuth")
	public ResponseBean getUserWithAuth(@RequestBody String str) throws MyException{
		logBefore(logger, "查询被授予权利的所用符合指定角色的人员(例如:查询高管)");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		String role_type = reqMap.get("role_type").toString();
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		if ("insideGG".equals(role_type)) {
			resultList = userService.getUserWithAuth();
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultList);
		}else {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultList);
		}
	}

	/**
	 * 校验权限并返回change_start
	 * @throws MyException
	 */
	@PostMapping("/checkOutAuth")
	public ResponseBean checkOutAuth(@RequestBody String str) throws MyException{
		logBefore(logger, "校验权限");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		String user_account = reqMap.get("user_account").toString();
		String user_password = MD5.md5(reqMap.get("user_password").toString());
		Map<String, Object> resultMap = userService.getAuthInfo(user_account);
		String correctPassword = resultMap.get("password").toString();
		if (user_password.equals(correctPassword)) {
			return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
		}
		return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "密码错误", null);
	}

	/**
	 * 解绑微信或者支付宝
	 * @throws MyException
	 */
	@PostMapping("/unbindWx")
	public ResponseBean unbindWx(@RequestBody String str, HttpServletRequest request) throws MyException {
		logBefore(logger, "解绑微信或者支付宝");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User user = getCurrentUser(request);
		Integer type = Integer.valueOf(reqMap.get("type").toString());
		userService.unbindWx(user, type);
		return new ResponseBean(Constants.CODE_SUCCESS, "解绑成功", null);
	}

	/**
	 * 绑定微信或者支付宝
	 * @throws MyException
	 */
	@PostMapping("/bindWx")
	public ResponseBean bindWx(@RequestBody String str, HttpServletRequest request) throws MyException, AlipayApiException {
		logBefore(logger, "绑定微信或者支付宝");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		User user = getCurrentUser(request);
		Integer type = Integer.valueOf(reqMap.get("type").toString());
		String authCode = reqMap.get("auth_code").toString();
		userService.bindWx(user, type, authCode);
		return new ResponseBean(Constants.CODE_SUCCESS, "绑定成功", userService.myBindWx(user));
	}
	/**
	 * 根据主机厂的id和省市的number查询服务商列表(主机厂下面的子服务商)
	 * @throws MyException
	 */
	@PostMapping("/getServerByArea")
	public ResponseBean bindWx(@RequestBody Map<String, Object> paramMap, HttpServletRequest request) throws MyException {
		logBefore(logger, "根据主机厂的id和省市的number查询服务商列表(主机厂下面的子服务商)");
		paramMap.put("sId", getCurrentUser(request).getS_id());
		PageInfo pageInfo =  userService.getServerByArea(paramMap);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", pageInfo);
	}

	/**
	 * 根据UserId和SId查询出该人员下面负责区域数据,并把区域数据封装为tree结构
	 * @throws MyException
	 */
	@PostMapping("/getWrapTreeWithAssignRegionUserBySId")
	public ResponseBean getUserInfo(@RequestBody Map<String, Object> paramsMap, HttpServletRequest request) throws MyException {
		logBefore(logger, "根据userId获取设置的区域列表信息");
		String sId = getCurrentUser(request).getS_id(); //获取当前用户的服务商id
		List<Map<String, Object>> regionList = appService.wrapTreeWithAssignRegionUserBySId(sId, paramsMap.get("userId").toString());
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", regionList);
	}

	/**
	 * 根据UserId修改主页推荐功能(在我的里面进行关闭打开) recommend_flag 1:默认打开 0：关闭
	 * @throws MyException
	 */
	@PostMapping("/openOrCloseRecommend")
	public ResponseBean openOrCloseRecommend(@RequestBody Map<String, Object> paramsMap, HttpServletRequest request) throws MyException {
		logBefore(logger, "根据userId设置推荐功能");
		userService.update(paramsMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
	}

	/**
	 * 检测账户名是否被注册(手机号) - 微信小程序等其他第三方
	 * 已注释: (and t1.status = '1' and t1.delete_flag = '0') or (status = 3(待审核) and delete_flag = 1)
	 * 已注释: 在用户状态为启用(status=1)并且未删除的(delete_flag=0)或者用户状态为待审核(status=3)并且删除的(delete_flag=1)的用户数据中检查是否存在
	 * 已注释: 查询出待审核的用户(车主)状态为待审核(status=3)并且删除的(delete_flag=1)；审核通过后设置status=1、delete_flag=0
	 * @throws MyException
	 */
	@PostMapping("/existUserInfoForWX")
	public ResponseBean existUserInfoForWX(@RequestBody String userAccount) {
		logBefore(logger, "检测账户名是否被注册(手机号) - 微信小程序等其他第三方");
		int count = userDao.existUserInfoForWX(userAccount);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", count);
	}

	/**
	 * 检测账户名是否被注册(手机号)，并发送MQ消息，使当前页面的源页面收到MQ消息并处理刷新等逻辑 - 微信小程序等其他第三方
	 */
	@PostMapping("/existUserInfoForWXBySendMQ")
	public ResponseBean existUserInfoForWXBySendMQ(@RequestBody Map<String, String> paramsMap) {
		logBefore(logger, "检测账户名是否被注册(手机号) - 微信小程序等其他第三方");
		Map<String, String> resultMap = userDao.getUser(paramsMap);

		String message = "{\"type\" : 4}";	// type = 4 : APP推广活动刷新源页面
		// routingKey 为虚拟的路由名称，与前端约定一致的路由名称(路由器需要设置为direct定向，把消息交给符合指定routing key的队列)
		RabbitTemplate rabbitTemplateForLogin = rmqlc.rabbitTemplateForLogin();
		rabbitTemplateForLogin.convertAndSend("amq.direct", paramsMap.get("shareAppQRPageForTimeMillisecond").toString(), message);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
	}

	/**
	 * 微信小程序等其他第三方-车主注册
	 * @throws MyException
	 */
	@PostMapping("/doRegisterCZForWX")
	public ResponseBean doRegisterCZForWX(@RequestBody Map<String, Object> paramsMap) {
		logBefore(logger, "微信小程序等其他第三方-车主注册");
		ResponseBean responseBean = new ResponseBean();
		int code = Constants.CODE_ERROR;
		String message = "";

		try {
			String userId = UuidUtil.get32UUID();  // 用户UUID主键
			paramsMap.put("id", userId);

			// 设置密码并对密码进行MD5加密
			String userPassword = paramsMap.get("user_password").toString();
			if(userPassword.equals("")) {
				userPassword = "123456";
			}
			paramsMap.put("user_password", MD5.md5(userPassword));
			paramsMap.put("user_name", Tool.secretMobilePhone(paramsMap.get("mobile_phone").toString()));  // 游客的设置用户名为手机号,手机号中间部分设置为✳
			paramsMap.put("pinyin_head", PinyinUtil.convertToPinyinIc(paramsMap.get("user_name").toString()));

			userDao.insertCarOwnerUserForWX(paramsMap);

			// 登录领取优惠券
			userCouponService.getCouponByRegister(userId, paramsMap.get("mobile_phone").toString());

			code = Constants.CODE_SUCCESS;
			message = "注册成功";
		} catch (Exception e) {
			code = Constants.CODE_ERROR;
			message = "发生异常";
			logger.error(e.toString(), e);
		} finally {
			responseBean.setCode(code);
			responseBean.setMessage(message);
			logAfter(logger);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
	}

    /**
     * 微信小程序等其他第三方-游客注册
     * @throws MyException
     */
    @PostMapping("/doRegisterYKForWX")
    public ResponseBean doRegisterYKForWX(@RequestBody Map<String, Object> paramsMap) {
        logBefore(logger, "微信小程序等其他第三方-游客注册");
        ResponseBean responseBean = new ResponseBean();
        int code = Constants.CODE_ERROR;
        String message = "";

        try {
            String userId = UuidUtil.get32UUID();  // 用户UUID主键
            paramsMap.put("id", userId);

            // 设置密码并对密码进行MD5加密
            String userPassword = paramsMap.get("user_password").toString();
            if(userPassword.equals("")) {
                userPassword = "123456";
            }
            paramsMap.put("user_password", MD5.md5(userPassword));
			paramsMap.put("user_name", Tool.secretMobilePhone(paramsMap.get("mobile_phone").toString()));  // 游客的设置用户名为手机号,手机号中间部分设置为✳
            paramsMap.put("pinyin_head", PinyinUtil.convertToPinyinIc(paramsMap.get("user_name").toString()));

            userDao.insertYKUserForWX(paramsMap);

            Map<String, Object> shareRecordMap = new HashMap<>(3);
            shareRecordMap.put("id", UuidUtil.get32UUID());
            shareRecordMap.put("user_id", paramsMap.get("sharerUserId")); // 分享者的主键ID
			shareRecordMap.put("share_type", 1); 						  // 分享活动的类型(1:APP分享;2:论坛分享)
            shareRecordMap.put("other_user_id", userId);                  // 分享后点击注册的用户的主键ID
            // 保存分享记录
            int result = shangJiMapper.insertShareRecord(shareRecordMap);
            if(result != 0) {	// 如果新用户添加成功，则调用分享送流量的逻辑
            	this.getTelAdressAndPercentage(paramsMap.get("sharerMobile").toString(), paramsMap.get("sharerUserId").toString());
			}

            // 登录领取优惠券
            userCouponService.getCouponByRegister(userId, paramsMap.get("mobile_phone").toString());

            code = Constants.CODE_SUCCESS;
            message = "注册成功";
        } catch (Exception e) {
            code = Constants.CODE_ERROR;
            message = "发生异常";
            logger.error(e.toString(), e);
        } finally {
            responseBean.setCode(code);
            responseBean.setMessage(message);
            logAfter(logger);
        }
        logAfter(logger);
        return new ResponseBean(code, message, null);
    }

	/**
	 * 微信小程序等其他第三方-游客注册分享的数据
	 * @throws MyException
	 */
	@PostMapping("/getShareRecordData")
	public ResponseBean getShareRecordData(@RequestBody Map<String, Object> paramsMap) {
		logBefore(logger, "微信小程序等其他第三方-游客注册分享的数据");
		Map<String, Object> resultMap = getTelAdressAndPercentage(paramsMap.get("mobile").toString(), paramsMap.get("userId").toString());
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
	}

	/**
	 * 添加活动的分享记录
	 * @param shareRecordMap
	 * @return
	 */
	@PostMapping("/saveShareRecord")
	public ResponseBean saveShareRecord(@RequestBody Map<String, Object> shareRecordMap) {
		logBefore(logger, "微信小程序等其他第三方 - 给分享给的助力用户添加助力记录");
		shareRecordMap.put("id", UuidUtil.get32UUID());
		int result = shangJiMapper.insertShareRecord(shareRecordMap); // 保存分享记录
		logAfter(logger);

		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
	}

	/**
	 * 把t_s_ss_mobile_isp表的 sended_reg 重置为 0，让其再次可以充值流量
	 * @param reqMap
	 * @return
	 */
	@PostMapping("/updateSendedReg")
	public ResponseBean updateSendedReg(@RequestBody Map<String, Object> reqMap) {
		logBefore(logger, "微信小程序等其他第三方 - 把 sended_reg 重置为 0，让其再次可以充值流量;同时更新分享的用户的删除标识为 1");
		int result = shangJiMapper.updateISPDataForSendedFlag(reqMap);  // 更新是否发送过分享注册用户送流量活动的流量的标识(ISP数据表) (null 表示未发送流量，1表示发送过)
		result += shangJiMapper.updateShareRecordForDeleteFlag(reqMap); // 更新分享的用户的删除标识为1(逻辑删除),不再计算逻辑删除的用户分享，使其可以重新计算分享的用户数
		logAfter(logger);

		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
	}

	/**
	 * 查询被分享人是否在活动中分享过(同一被分享人只能助力一次)
	 * @param reqMap
	 * @return
	 */
	@PostMapping("/existOtherUserForShareRecord")
	public ResponseBean existOtherUserForShareRecord(@RequestBody Map<String, Object> reqMap) {
		logBefore(logger, "微信小程序等其他第三方 - 查询被分享人是否在活动中分享过(同一被分享人只能助力一次)");
		Map<String, Object> result = shangJiMapper.existOtherUserForShareRecord(reqMap); // 保存分享记录
		logAfter(logger);

		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
	}

	/**
	 * 查询服务商审核小程序扫码用户 status:3 待审核，delete_flag:1  扫码注册的用户默认为1
	 * @throws MyException
	 */
	@PostMapping("/getExamineUserList")
	public ResponseBean getExamineUserList(@RequestBody Map<String, Object> paramsMap, HttpServletRequest request) throws MyException {
		logBefore(logger, "查询服务商审核小程序扫码用户");
		String sId = getCurrentUser(request).getS_id(); //获取当前用户的服务商id
		paramsMap.put("s_id",sId);
		PageInfo pageInfo =userService.getExamineUserList(paramsMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", pageInfo);
	}

	/**
	 * 服务商审核通过小程序扫码用户 status:1 正常，delete_flag:0  扫码注册的用户修改为0 可登录
	 * @throws MyException
	 */
	@PostMapping("/approveExamineUser")
	public ResponseBean approveExamineUser(@RequestBody Map<String, Object> paramsMap, HttpServletRequest request) throws MyException {
		logBefore(logger, "服务商审核通过小程序扫码用户");
		String sId = getCurrentUser(request).getS_id(); //获取当前用户的服务商id
		paramsMap.put("s_id",sId);
		userService.approveExamineUser(paramsMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
	}

	/**
	 * 服务商审核通过小程序扫码用户 status:1 正常，delete_flag:0  扫码注册的用户修改为0 可登录
	 * @throws MyException
	 */
	@PostMapping("/refuseExamineUser")
	public ResponseBean refuseExamineUser(@RequestBody Map<String, Object> paramsMap, HttpServletRequest request) throws MyException {
		logBefore(logger, "服务商审核通过小程序扫码用户");
		String sId = getCurrentUser(request).getS_id(); //获取当前用户的服务商id
		paramsMap.put("s_id",sId);
		userService.refuseExamineUser(paramsMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
	}

	/**
	 * 检验并获取本地的手机号码的ISP信息，并构造返回分享进度
	 * @param mobile
	 * @param userId
	 * @return
	 */
	private Map<String, Object> getTelAdressAndPercentage(String mobile, String userId) {
		Map<String, Object> ispData = shangJiMapper.getISPDataWithLocal(mobile); // 根据Mobile手机号码查询本地库是否存在手机相关ISP信息
		if(ispData == null) { // 如果本地数据库内未保存远端API的ISP数据则需要获取并保存到数据库
			String remoteUrl = "https://eolink.o.apispace.com/teladress/teladress";
			HttpHeaders headers = new HttpHeaders();	// 请求头
			headers.add("X-APISpace-Token", xAPISpaceToken);
			headers.add("Authorization-Type", "apikey");
			headers.add("Content-Type","application/x-www-form-urlencoded");
			MultiValueMap<String, String> map = new LinkedMultiValueMap<>();	// 请求体
			map.add("mobile", mobile);
			HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
			ResponseEntity<JSONObject> response = restTemplate.postForEntity(remoteUrl, request, JSONObject.class);	// 使用RestTemplate请求
			if(response.getStatusCodeValue() == 200) { // 如果响应正确，则添加到数据库内
				JSONObject bodyRespnse = response.getBody();
				ispData = (Map<String, Object>)bodyRespnse.get("data");
				shangJiMapper.insertMobileISP(ispData); // 保存第三方API返回的手机的ISP信息数据到本地数据库
			}
		}

		String currentMobileISP = ispData == null ? "移动" : ispData.get("isp").toString();
		Map<String, Integer> settingMap = new HashMap<>();
		settingMap.put("移动", 3);
		settingMap.put("联通", 4);
		settingMap.put("电信", 6);
		String percentage = "99.99";
		int sharedCount = shangJiMapper.countSharePerson(userId, 1);
		if(sharedCount > 0) {
			int settingValue = settingMap.get(currentMobileISP);
			int floor = sharedCount % settingValue; // 取余
			logger.info(floor + "");

			if(floor != 0) {
				if (sharedCount < settingValue) {
					int point = 10 - (settingValue - sharedCount);
					percentage += point;
				} else if (sharedCount > settingValue) {
					int point = 10 - (settingValue - floor);
					percentage += point;
				}
			} else { // floor 等于 0，也就是表示整除可以除尽(进度到达 100%) ; 分享人数与既定的数量的整数倍时，才需要进行流量充值(可以多次分享)
				percentage = "100";

				boolean sendedForReg = ispData.get("sended_reg") == null ? false: (boolean)ispData.get("sended_reg");	// 同一手机号满足条件且当前分享轮次未充值时，才需要进行流量充值
				if(!sendedForReg) {
					Map<String, String> productIdMap = new HashMap<>();
					productIdMap.put("移动", "0010201001024");
					productIdMap.put("联通", "0020201001024");
					productIdMap.put("电信", "0030201002048");

					Map<String, String> dataTrafficTypeMap = new HashMap<>();
					dataTrafficTypeMap.put("移动", "1G");
					dataTrafficTypeMap.put("联通", "1G");
					dataTrafficTypeMap.put("电信", "2G");

					// 测试的充值不到账，需要回退的流量商品 - 移动
					// productIdMap.put("移动", "0010401002048");

					String productId = productIdMap.get(currentMobileISP);

					logger.info(kapoolUserId);
					logger.info(mobile);
					logger.info(productId);
					logger.info(kapoolSign);
					String key = MD5.md5(kapoolUserId + mobile + productId + kapoolSign);
					logger.info(key);

					// 调用代理商的发放流量的接口
					String sendFlowOrderAPIOfKaChi = "http://open.kp-api.com/ms/sendFlowOrderAPI";
					MultiValueMap<String, String> map = new LinkedMultiValueMap<>();	// 请求体
					map.add("userid", kapoolUserId);
					map.add("mobile", mobile);
					map.add("bizid", UuidUtil.get32UUID());
					map.add("productid", productId);
					map.add("buynum", "1");
					map.add("notifyurl", "www.zoweunion.com");
					map.add("key", key);
					HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, null);
					ResponseEntity<JSONObject> response = restTemplate.postForEntity(sendFlowOrderAPIOfKaChi, request, JSONObject.class);	// 使用RestTemplate请求
					String resultCode = response.getBody().get("resultCode").toString();
					logger.info(response.getBody().toJSONString());
					if(response.getStatusCodeValue() == 200 && resultCode.equals("T00001")) {	// 如果响应正确，则更新是否发送过分享注册用户送流量活动的流量的标识(ISP数据表)到数据库内
						String smsContent = String.format(SmsUtil.AppPromotionActivityTraffic1Successful,dataTrafficTypeMap.get(currentMobileISP));
						logger.info("发送到手机号码：" + mobile + "，内容为：" + smsContent);
						SmsUtil.sendSms(mobile, smsContent); // APP推广活动1成功获取流量后的短信提醒

						ispData.put("sended_reg", 1);
						shangJiMapper.updateISPDataForSendedFlag(ispData);	// 更新是否发送过分享注册用户送流量活动的流量的标识(ISP数据表)
					}
				}
			}
		}
		logger.info(percentage);

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("percentage", percentage);
		return resultMap;
	}

	public static void main(String[] args) {
		System.out.println(UuidUtil.get32UUID());
		System.out.println(MD5.md5("13861888505"));
		System.out.println(MD5.md5("P44202519c76a5f44c95892d2c929ec54bb7e4"));
		System.out.println(MD5.md5("P44202150522184130010401002048519c76a5f44c95892d2c929ec54bb7e4"));
	}
}